import { Book } from "@/types/book";

/* * @Author: su  * @Date: 2025-04-30 14:00:26   */
const tableName: string = 'keyvaluepairs'; //数据库表/存储对象
let db: any // 数据库实例
let request: any
const SQL_NAME: string = 'onlineReadDB';//数据库名称


function init():Promise<IDBDatabase> {
    return new Promise<IDBDatabase>((resolve, reject) => {
        // 打开数据库SQL_NAME ，如果没有SQL_NAME数据库会创建一个
        request = window.indexedDB.open(SQL_NAME);
        //数据库打开报错
        request.onerror = (event: any) => {
            reject(event);
            console.log('缓存获取失败');
        };

        //数据库打开成功
        request.onsuccess = (event: any) => {
            console.log('数据库打开成功')
            db = (event.target as IDBOpenDBRequest).result;
            resolve(db);
            db.onerror = function (error: any) {
                console.log('error---------', error)
            }
        };
        //当数据库的版本更新时当试图打开一个尚未被创建的数据库，或者试图连接一个数据库还没被创立的版本时，
        // onupgradeneeded 事件会被触发触发
        request.onupgradeneeded = (event: any) => {
            ////获取打开（或正在升级）的数据库对象
            db = (event.target as IDBOpenDBRequest).result;
            // 检查数据库中是否存在指定的对象存储（表）  
            if (!db.objecttableNames?.contains(tableName)) {
                // 如果不存在，则创建一个新的对象存储 （表）
                // 在对象存储中创建索引，以便能够高效地通过指定字段查询记录  
                db.createObjectStore(tableName)
                // objectStore = db.createObjectStore(tableName, {
                //     keyPath: "name",
                //     unique: true, // 名称作为主键不允许重复
                // });
            }
        };
    });
}
async function add(key: string, content:any) {
    return new Promise((resolve, reject) => {
        // 打开数据库上的事务，然后打开一个对象存储，添加数据
        const select = db
            .transaction([tableName], "readwrite") // 启动需要访问的表，并设置读写权限(默认只有读取权限)
            .objectStore(tableName) // 获取指定名称的对象存储（表）
            .add(content, key); //添加数据

        select.onsuccess = (event: any) => {
            console.log('数据写入成功------', event.target.result)
            resolve(event.target.result);
        };
        select.onerror = reject;
    });
}
async function get(key: string) {
    return new Promise<any>((resolve, reject) => {
        const transaction = db.transaction([tableName], "readonly");
        const objectStore = transaction.objectStore(tableName);
        const request = objectStore.get(key);

        request.onsuccess = function () {
            if(request.result){
                resolve(request.result);
            }else{
                reject(null)
            }
        };
        request.onerror = reject;
    });
}
async function update(key: string, content: string | Blob | Book[]) {
    return new Promise((resolve, reject) => {
        const select = db
            .transaction([tableName], "readwrite")
            .objectStore(tableName)
            .put(content, key);

        select.onsuccess = (event: any) => {
            resolve(event.target.result);
        };
        select.onerror = reject;
    });
}


export default {
    init,
    add,
    get,
    update,
};